#include "MainWindowFrame.h"
#include "ui_MainWindowFrame.h"

#include "Remote.h"

#include <QThread>
#include <QtConcurrent>

#include <opencv2/opencv.hpp>

#define THREAD_INFO() (qDebug() << __FUNCTION__ << QThread::currentThread())

MainWindowFrame::MainWindowFrame(QWidget *parent) :
    QFrame(parent),
    ui(new Ui::MainWindowFrame)
    ,_cameraFlag(false)
    , _data(nullptr)
{
    THREAD_INFO();
    ui->setupUi(this);
}

MainWindowFrame::~MainWindowFrame()
{
    _cameraFlag = false;
    this->_fut.cancel();
    delete ui;
}

void MainWindowFrame::showVideo()
{
    //读取视频或摄像头
    QMutexLocker locker(&_mutex);
    cv::VideoCapture capture(0);

    while (_cameraFlag)
    {
        cv::Mat frame;
        capture >> frame;

        cv::Mat temp;
        cvtColor(frame, temp, CV_BGR2RGB);//BGR convert to RGB
        QImage Qtemp = QImage((const unsigned char*)(temp.data), temp.cols, temp.rows, temp.step, QImage::Format_RGB888);
        ui->label->setPixmap(QPixmap::fromImage(Qtemp));
        THREAD_INFO();
    }
}

void MainWindowFrame::on_cameraBtn_clicked()
{
    THREAD_INFO();
#if 0
    _cameraFlag = !_cameraFlag;
    if(_cameraFlag == false) return;
        _fut = QtConcurrent::run(this, &MainWindowFrame::showVideo);
//    fut1.waitForFinished();
#endif
        QtConcurrent::run(this, &MainWindowFrame::testDelete);
        QtConcurrent::run(this, &MainWindowFrame::testDelete);
}

void MainWindowFrame::on_toolBtnListen_clicked()
{
    Remote remote;
    // 监听外部时间
    _fut = QtConcurrent::run(&remote, &Remote::listen_event);
}

void MainWindowFrame::testDelete()
{
    QMutexLocker lock(&_mutex);
    THREAD_INFO();
    while(1)
    {
        if(_data != nullptr) delete _data;
        _data = new char;
        QThread::sleep(1);
    }
}
